package com.carl.zlds.service.impl;

import com.carl.zlds.tool.exception.GlobalException;
import com.carl.zlds.tool.util.AssertUtil;
import com.carl.zlds.tool.util.ObjUtil;
import com.carl.zlds.tool.util.PasswordHash;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carl.zlds.dao.AdminMapper;
import com.carl.zlds.model.Admin;
import com.carl.zlds.model.Token;
import com.carl.zlds.pojo.dto.SaveAdminDTO;
import com.carl.zlds.pojo.vo.AdminVO;
import com.carl.zlds.service.IAdminService;
import com.carl.zlds.service.ITokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author carl
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private final ITokenService tokenService;

    @Autowired
    public AdminServiceImpl(ITokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public Map<String, Object> login(SaveAdminDTO dto) {
        String username = dto.getUsername().trim();
        String password = dto.getPassword().trim();

        Wrapper<Admin> wrapper = new QueryWrapper<Admin>()
                .eq("username", username)
                .eq("weight", 0);
        Admin admin = this.baseMapper.selectOne(wrapper);
        AssertUtil.isNull("管理员不存在", admin);

        try {
            if (!PasswordHash.validatePassword(password, admin.getPassword())) {
                AssertUtil.exception(GlobalException.ERROR_NOT_ALLOWED, "密码错误");
            }
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }

        Token tokenEntity = tokenService.getBaseMapper().selectOne(new QueryWrapper<Token>()
                .eq("user_id", admin.getId())
                .eq("status", 1)
                .eq("weight", 0));
        String tokenResp = "";
        if (tokenEntity == null) {
            String t = Token.makeToken();
            Token token = new Token();
            token.setToken(t);
            token.setUserId(admin.getId());
            token.setStatus(1);
            tokenService.getBaseMapper().insert(token);
            tokenResp = t;
        } else {
            tokenResp = tokenEntity.getToken();
        }

        HashMap<String, Object> map = new HashMap<>(2);
        map.put("admin", ObjUtil.processModel(admin, AdminVO.class));
        map.put("token", tokenResp);
        return map;
    }

    @Override
    public void logout(String token) {
        Token tokenEntity = tokenService.getBaseMapper().selectOne(new QueryWrapper<Token>()
                .eq("token", token)
                .eq("weight", 0));
        tokenEntity.setStatus(0);
        tokenEntity.setWeight(-1);
        tokenService.updateById(tokenEntity);
    }
}
